#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gui import *
from gameinit import *
from player import *
from gamewidgets import Minimap,Pix2Hex,HexDetails,miniMapOnClick,WindowMap
from ship import Ship
        
class WindowMapEditor(WindowMap):
    REFRESH_ON_MOUSE_OVER = True
    REFRESH_ON_MOUSE_DOWN = True
    REFRESH_ON_MOUSE_CLICK = True
    REFRESH_ON_MOUSE_LEAVE = True
    SELECTMODE = 0
    DRAWMODE = 1
    
    def __init__(self, boardmap , position = (0,0),size=(800,600), parent = None, style = None, enabled = True):
        WindowMap.__init__(self, boardmap , position,size, parent , style , enabled )

        # Editor variables :
        self.currHex2Draw = boardmap.hexs[0].clone()
        self.status = WindowMapEditor.SELECTMODE

    def rotateHex(self,theta = 1):
        pos = self.currHex2Draw.pos
        pos += theta
        if pos < 0:
            pos +=6
        if pos >=6:
            pos = pos % 6
        self.currHex2Draw.pos = pos

    def update(self,topmost):
        Widget.update(self, topmost)
    #    pass
        if self.hasFocus:
            if len(gui.events) > 0:
                
                for e in gui.events:
                    #print e.type
                    if e.type == pygame.KEYDOWN:
                        if e.key == pygame.K_LEFT: self.rotateHex(1)
                        elif e.key == pygame.K_RIGHT: self.rotateHex(-1)
                    
                    if e.type == pygame.MOUSEBUTTONDOWN:
                        if e.button == 4 and self.mouseover: #Wheel-UP
                            self.rotateHex(1)
                            
                        if e.button == 5 and self.mouseover: #Wheel-down
                            self.rotateHex(-1)
                    

    def getHexCoords(self):
        return self.hexX, self.hexY

    def setCurrHex2Draw(self,hexa):
        self.currHex2Draw = hexa

    def putHex(self,coord):
        newHex = self.currHex2Draw.clone()
        newHex.coord = coord
        self.board.setHex(newHex)

    def activateDraw(self):
        self.status = WindowMapEditor.DRAWMODE

    def activateSelect(self):
        self.status = WindowMapEditor.SELECTMODE

    def handleClick(self,coord):
        if self.status == WindowMapEditor.SELECTMODE:
            x,y = coord
            h = self.board.getHex(x,y)
            player = self.board.currentPlayer
            player.unselect()
            player.select(h)
        
        elif self.status == WindowMapEditor.DRAWMODE:
            self.putHex(coord)
            player = self.board.currentPlayer
            player.unselect()
            player.select(self.currHex2Draw)
        


# For the window map display

def WindowMapOnClick(windowMapEditor):
    x0,y0 = windowMap.position
    topleftHexCoord = windowMap.getHexCoords
    xm,ym = pygame.mouse.get_pos()
    side = mapTiles.side
    coord = (xm-x0,ym-y0)
    
    x,y = Pix2Hex(coord,side,topleftHexCoord)
    windowMapEditor.handleClick((x,y))


class HexCollection(object):
    def __init__(self,players,path="data/hexs/"):
        self.side = 35
        self.hexs = []
        self.load(players,path)

    def load(self,players,path):
        hexfiles = os.listdir(path)
        for filename in hexfiles:
            if filename.endswith(".txt"):
                properties = {}
                f = open(path+filename)
                for line in f.readlines():
                    key,value = line.replace(" ","").replace("\n","").replace("\r","").split("=")
                    properties[key] = value
                f.close()
                hexConst = id2hexConst[properties["type"]]
                
                skin = properties["img"]
                if skin=="None":
                    skin = None
                self.hexs.append(hexConst((0,0),0,skin,players))

    def getHexs(self):
        return self.hexs
    

def buttonSave_onClick(button):
    win = Window(position = (300,220), size = (400,200), parent = desktop, text = "Save map" )
    Label(position = (10,40), parent = win, text = "Save as")
    win.textbox = TextBox(position = (10, 60), parent = win) 
    b = Button(position = (310,70), size = (80,0) , parent= win, text = "Save")
    b.onClick = lambda button:  windowMap.board.save("data/shipmaps/%s.txt" % win.textbox.text) or win.close() 

def dbg(x):
    print x 

def buttonLoad_onClick(button):
    win = Window(position = (300,220), size = (400,200), parent = desktop, text = "Load map" )
    Label(position = (10,40), parent = win, text = "Load map : ")

    items = os.listdir("data/shipmaps/")
    for item in items:
        if not item.endswith('.txt'):
            items.remove(item)
    
    win.listBoxFiles = ListBox(position = (10,90), size = (150, 80), parent = win,  items = items)
    #win.add()
    
    b = Button(position = (310,70), size = (80,0) , parent= win, text = "Load")
    b.onClick = lambda button: windowMap.board.load("data/shipmaps/%s" % win.listBoxFiles.items[win.listBoxFiles.selectedIndex]) or minimapship.refreshBoard() or win.close()

def createMap(mapType,size):
    players = windowMap.board.getPlayers()
    if mapType == "Ship":
        windowMap.board = Ship(size,players)
    else:
        windowMap.board = board(size,players)
    minimapship.board = windowMap.board
    minimapship.refreshBoard()
    

def buttonNew_onClick(button):
    win = Window(position = (300,220), size = (400,200), parent = desktop, text = "New map" )
    Label(position = (10,40), parent = win, text = "Size")
    win.textboxW = TextBox(position = (10, 60),size = (20,20), parent = win,text="15")
    win.textboxH = TextBox(position = (30, 60),size = (20,20), parent = win,text="15")
    win.listBoxFiles = ListBox(position = (10,85), size = (150, 80), parent = win,  items = ["Ship","Space"])
    b = Button(position = (310,70), size = (80,0) , parent= win, text = "Create")

    b.onClick = lambda button: \
                createMap(win.listBoxFiles.items[win.listBoxFiles.selectedIndex],(int(win.textboxW.text),int(win.textboxH.text))) \
                or win.close()

        
if __name__ == "__main__":
    import pygl2d
    import gui
    from board import *
    import defaultStyle

    defaultStyle.init(gui)

    winWidth = 12
    winHeight = 8

    # Init GUI
    desktop = gui.Desktop()
    
    
    player = Player("editor") 
    players = [player]
    
    ship = board("data/shipmaps/shiptest2.txt",players)
    ship.setCurrentPlayer(player)

    windowMap=WindowMapEditor(ship,position = (0,0),size=(800,SCREEN_HEIGHT), parent = desktop)
    windowMap.status = 1 # DRAW
    winHexSize=windowMap.getWindowHexSize()

    minimapSize = (210,210)
    minimapship = Minimap(ship,position = (SCREEN_WIDTH-minimapSize[0],0),size=minimapSize,winHexSize=winHexSize, parent = desktop)
    hexDetails = HexDetails(player,position=(SCREEN_WIDTH-210,210),size=(210,100),parent = desktop)


    # Link Callbacks
    minimapship.onClick = miniMapOnClick
    windowMap.onClick = WindowMapOnClick
    
    hexCollection = HexCollection(players)
    items = []
    for h in hexCollection.getHexs():
        items.append(type(h).description)
    listBoxHexs = ListBox(position = (850,315), size = (150, 120), parent = desktop,  items = items)

    # BUTTONS

    buttonNew = Button(position = (870, 450), size = (100,20), parent = desktop, text = "New")
    buttonNew.onClick = buttonNew_onClick
    buttonSave = Button(position = (870, 475), size = (100,20), parent = desktop, text = "Save")
    buttonSave.onClick = buttonSave_onClick
    buttonLoad = Button(position = (870, 500), size = (100,20), parent = desktop, text = "Load")
    buttonLoad.onClick = buttonLoad_onClick
    

    print listBoxHexs
    
    print pygame.display.get_surface().get_size()
    
    clock = pygame.time.Clock()
    running = 1

    while running:
        clock.tick(60.0)
         
        for e in gui.setEvents():
            
            if e.type == QUIT:
                running = 0
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    running = 0
       
        desktop.update()
        if listBoxHexs.hasBeenRefreshed:
            windowMap.setCurrHex2Draw(hexCollection.getHexs()[listBoxHexs.getSelectedIndex()])

        pygl2d.window.begin_draw()
        x0,y0,x1,y1 = minimapship.getWindowHex()

        windowMap.updateCoords(x0,y0)
        
        desktop.draw()
        
        pygl2d.window.end_draw()
        pygame.display.flip()
        display.set_caption(str(int(clock.get_fps())))

        
        

    pygame.quit()
    

    
